<?php

namespace App\Http\Controllers;

use App\Post;
use Illuminate\Http\Request;
use App\Http\Requests;
use Carbon\Carbon;

class BlogController extends Controller
{
    public function index()
    {
        $posts = Post::where('published_at', '!=', Carbon::now())
            ->orderBy('id', 'desc')
            ->paginate(config('blog.posts_per_page'));

        return view('blog.index', compact('posts'));
    }

    public function showPost($slug)
    {
        $post = Post::whereSlug($slug)->firstOrFail();
        return view('blog.post')->withPost($post);
    }


    public function create()
    {
        return view('blog.create');
    }

    public function store(Request $request)
    {
        $this->validate($request, [
            'title' => 'required|unique:posts|max:191',
            'content' => 'required',
        ]);

        $article = new Post;
        $article->title = $request->input('title');
        $article->content = $request->input('content');
        $article->slug = $request->input('title');

        if ($article->save()) {
            return redirect('blog');
        } else {
            return redirect()->back()->withInput()->withErrors('保存失败！');
        }
    }
    public function destroy($id)
    {
        Post::find($id)->delete();
        return redirect()->back()->withInput()->withErrors('删除成功！');
    }
}